import { defineStore } from 'pinia'

/* 个人中心 */
export default defineStore('userStore', {
	state: () => ({
			access_token: '' as string,
			fresh_token: '' as string,
			showAuth: false,
			id: 0 as number,
			avatar: '' as string,
			nickname: '' as string,
			mobile: '' as string, 
			timsig: '' as string,
			msgs: [],
			convs: [],
			unreadCount: 0 as number,
			uid: '' as string,
			history: [],
			todo: { matter: 0, item: 0, order: 0 as number, refund: 0 as number, comment: 0 as number, receive: 0 as number},
			sell: {}, // 销售数据
			cart: []
	}),
	getters: {
		// 验证身份,是否已授权
		auth () {
			return this.access_token || this.fresh_token
		},
		cartCount () {
			let count = 0
			this.cart.map((r: {number: number}) => {
				count += r.number
			})
			return count
		}
	},
	actions: {
		update(values: object) {
			Object.assign(this, values)
		},
		clear() {
			this.id = 0
			this.nickname = ''
			this.avatar = ''
			this.access_token = ''
			this.fresh_token = ''
		},
		conv(list: {conversationID: string}[]) {
			const userID = 'agent-' + this.id
			const data = {} as any
			list.map((r: {conversationID: string}) => {
				data[r.conversationID] = r
			})
			const news = [] as any[]
			const convs = uni.getStorageSync('convs-' + userID) || []
			convs.map((r: {conversationID: string}, i: number) => {
				if(data[r.conversationID]){
					list[i] = data[r.conversationID]
					!news.findIndex(row => r.conversationID == row.conversationID) !== false && news.push(r.conversationID)
				}
			})
			uni.setStorageSync('convs-' + userID, list.filter(r=>!news.includes(r.conversationID)).concat(convs))
			this.convs = uni.getStorageSync('msgs-' + userID)
		},
		msg(list: object[]) {
			const userID = 'agent-' + this.id
			const msgs = uni.getStorageSync('msgs-' + userID) || []
			uni.setStorageSync('msgs-' + userID, list.concat(msgs))
			this.msgs = uni.getStorageSync('msgs-' + userID)
		},
		// 设置令牌
		login(res: object) {
			Object.assign(this, res)
			/*
			uni.$tim.login({
				userID: 'user' + res.id, 
				userSig: res.timsig,
			}).then(resp=>{
				
			}).catch(error=>{
				// console.warn('login error:', error); // 登录失败的相关信息
			})
			*/
		},
		// 设置令牌
		fresh(access_token: string) {
			this.access_token = access_token
		},
		logout() {
			Object.assign(this, {access_token: '', fresh_token: '', avatar:'', nickname:'', mobile:'', id: 0})
		},
		updateCart(item: {id: number, number: number}){
			if(!this.cart.some((r,i) => r.id==item.id && (this.cart[i].number = item.number))){
				this.cart.push(item)
			}
		}
	},
	persist: {
		// enabled: true,
		// 调整为兼容多端的API
		storage: {
			getItem(key: string) {
				return uni.getStorageSync(key)
			},
			setItem(key: string, value: any) {
				uni.setStorageSync(key, value)
			}
		}
	}
})
